package com.beans;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.inject.Inject;
import javax.inject.Named;

import org.primefaces.event.SelectEvent;
import org.primefaces.model.DualListModel;
import org.springframework.context.annotation.Scope;

import com.controllers.GroupController;
import com.controllers.RoleController;
import com.model.Group;
import com.model.Role;

@Named
@Scope(value = "request")
public class GroupBean implements Serializable {

	private static final long serialVersionUID = 244219072819116038L;

	private GroupController groupController;
	
	private Group group;

	private DualListModel<Role> roles;

	private List<Group> allGroups;

	private List<Role> selectedRoles;

	private final List<Role> allRoles;

	@Inject
	public GroupBean(GroupController groupController, RoleController roleController) {
		this.groupController = groupController;
		allGroups = groupController.getGroups();
		allRoles = roleController.getRoles();
		selectedRoles = new ArrayList<Role>();
		roles = new DualListModel<Role>(new ArrayList<Role>(), selectedRoles);
		group = new Group();
	}

	public void save(ActionEvent actionEvent) {
		group.getRoles().clear();
		group.getRoles().addAll(roles.getTarget());
		groupController.saveGroup(group);
		FacesContext.getCurrentInstance().addMessage(
				null,
				new FacesMessage("El grupo "
						+ group.getName() +" ha sido actualizado exitosamente"));
	}

	public void refreshRoles(SelectEvent event) {

		group = (Group) event.getObject();
		List<Role> groupRoles = groupController
				.getRolesByGroup(group.getId());
		intersectActions(groupRoles);
		roles = new DualListModel<Role>(allRoles, groupRoles);
		FacesContext.getCurrentInstance().addMessage(
				null,
				new FacesMessage("Editando grupo :"
						+ " " + group.getName()));
	}

	private void intersectActions(List<Role> groupRoles) {
		for (Role selected : groupRoles)
			for (Role role : allRoles) {
				{
					if (role.getId() == selected.getId()) {
						allRoles.remove(role);
						break;
					}
				}
			}
	}

	public Group getGroup() {
		return group;
	}

	public void setGroup(Group group) {
		this.group = group;
	}

	public DualListModel<Role> getRoles() {
		return roles;
	}

	public void setRoles(DualListModel<Role> roles) {
		this.roles = roles;
	}

	public List<Group> getAllGroups() {
		return allGroups;
	}

	public void setAllGroups(List<Group> allGroups) {
		this.allGroups = allGroups;
	}

	public List<Role> getSelectedRoles() {
		return selectedRoles;
	}

	public void setSelectedRoles(List<Role> selectedRoles) {
		this.selectedRoles = selectedRoles;
	}

	
}
